<?php
/*
 * content : 认证权限类
 * Author  : Songyicong
 * time    : 2018-04-17 15:32:15
 * email   : m13726262373@163.com
 */
namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\controller\Factory;
use app\api\extra\Send;
use app\api\extra\Utils;
use app\api\model\Oauth as Oauth;
use think\Cache;
use think\Request;
use app\api\service\v1\TokenService;

class Token extends BaseController{

    use Send;

    public $tokenAuth = false;
    protected $tokenService;

    /** 初始化检测请求时间，签名 */
    public function __construct(){
        parent::__construct();
        $this->tokenService = new TokenService();
        // 为了调试注释掉时间验证与前面验证，请开发者自行测试
        // $this->checkTime();
        // $this->checkSign();
    }


    /** 检测时间 +- 300秒内请求的问题,超时拒接 */
    public function checkTime(){
        $time = $this->request->param('timestamp');
        if ($time > time() + 300 || $time < time() - 300) {
            return $this->returnmsg(401, 'The request time is incorrect');
        }
    }

    /** 检查签名 */
    public function checkSign(){
        $baseAuth = Factory::getInstance(\app\api\controller\Oauth::class);
        $appinfo = Oauth::getSecret(['client_id' => $this->request->param('client_id'),'secret' => $this->request->param('app_secret')]);
        $sign = $baseAuth->makesign($this->request->param(), $appinfo['app_secret']); //生成签名
        if ($sign !== $this->request->param('signature')) {
            //判断签名是否正确
            return self::returnmsg(401, 'Signature error', [], []);
        }
    }

    /** 设置AccessToken */
    public function setAccessToken(){
        $this->tokenService->setAccessToken($this->params);
    }

    /** 更新access_token */
    public function referAccessToken(){
        $this->tokenService->updateAccessToken($this->params);
    }

}
